package com.autohammal.monitor.scheduler.implement;

import com.autohammal.monitor.scheduler.Scheduler;
import com.autohammal.monitor.scheduler.support.MonitorTimer;
import com.autohammal.monitor.scheduler.support.MonitorTimerTask;
import com.autohammal.monitor.scheduler.support.SchedulerUnit;

public class SimpleMonitorScheduler implements Scheduler {
	private static final long serialVersionUID = -4185468898105981135L;
	private SchedulerUnit scheduleUnit;
	private MonitorTimer timer = null;

	public void setScheduleUnit(SchedulerUnit scheduleUnit) {
		this.scheduleUnit = scheduleUnit;
	}

	public SchedulerUnit getScheduleUnit() {
		return scheduleUnit;
	}

	public SimpleMonitorScheduler() {
		super();
	}

	public SimpleMonitorScheduler(SimpleMonitorScheduler smc) {
		super();
		setScheduleUnit(smc.getScheduleUnit());
	}

	@Override
	public void schedule(final Runnable runnable) {
		MonitorTimerTask task = new MonitorTimerTask() {
			@Override
			public void run() {
				runnable.run();
			}
		};
		this.cancel();
		timer = new MonitorTimer();
		timer.schedule(task, scheduleUnit.getFirst(), scheduleUnit.getPeriod());
	}

	@Override
	public void cancel() {
		if (timer != null)
			timer.cancel();
		timer = null;
	}

}
